import 'dart:convert';

import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';

import '../model/EcyApiCommonPage.dart';
import '../model/EcyApiCommonResponse.dart';
import '../model/EcyLocationModel.dart';
import 'EcyRequestBaseManager.dart';

///网络请求类
class EcyLocationManager {
  factory EcyLocationManager() => _instance;
  static late final EcyLocationManager _instance =
      EcyLocationManager._internal();

  EcyLocationManager._internal() {
    EcyLogger.log("EcyLocationManager init");
  }

  late Position _currentPosition;
  List<Placemark> _placemarks = [];
  bool serviceEnabled = false;
  late LocationPermission permission;

  Future<EcyLocationModel?> getCurrentLocation() async {
    // 检查位置服务是否启用
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    _currentPosition = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );

    // 可选：将经纬度转换为地址
    _placemarks = await placemarkFromCoordinates(
        _currentPosition.latitude, _currentPosition.longitude);
    if (_placemarks != null && _placemarks.isNotEmpty) {
      EcyLocationModel locationModel = EcyLocationModel();
      locationModel.lng = _currentPosition.longitude.toString();
      locationModel.lat = _currentPosition.latitude.toString();
      return locationModel;
    } else {
      return null;
    }
  }

  Future<EcyLocationModel?> getDefaultAddress() async {
    Map<String, dynamic> body = {
      "pageSize": 50,
      "pageIndex": 1,
    };
    var response =
        await EcyRequestbasemanager().get("/app/api/app/user/address/list", body);

    if (response != null) {
      var respModel =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (respModel.code == 0 || respModel.code == 200) {
        EcyApiCommonPage<EcyLocationModel> modelPage =
            EcyApiCommonPage.fromJson(
                response["data"], (json) => EcyLocationModel.fromJson(json));
        var records = modelPage.records ?? [];
        if (records.isNotEmpty) {
          return records[0];
        }
      }
    }
    return null;
  }
}
